package com.xframe.xdal.core.model.sqlbuilder.proc;


import com.xframe.xdal.core.constant.*;
import com.xframe.xdal.core.model.mapping.*;
import com.xframe.xdal.core.model.sqlbuilder.*;
import lombok.Data;
import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;
import java.util.List;


/**
 * 功能描述: 保存数据 sqlBuiler
 *
 * @author xufeng
 * @version 1.0
 * @date 2022-09-26
 */
@Log4j2
@Data
public class DefSaveBuilder extends BaseSqlBuilder {

    /**
     * 保存数据sql表达式模板
     *
     * @return
     */
    public String getSQL() {
        return "INSERT INTO %s(%s) VALUES(%s)";
    }


    /**
     * 构建sql表达式对象
     *
     * @param context 上下文
     * @return SqlExpression
     */
    @Override
    public SqlExpression build(BuilderContext context) {

        List<IColumnMapping> columnMappings = context.findNotDbGenerated();
        log.info("columnMappings = {}", columnMappings);
        StringBuilder colstrBuilder = new StringBuilder();
        StringBuilder valstrBuilder = new StringBuilder();
        List<Object> pList = new ArrayList<>();
        for (int index = 0; index < columnMappings.size(); index++) {
            IColumnMapping columnMapping = columnMappings.get(index);
            colstrBuilder.append(context.getNameConvert().toName(columnMapping.getName()));
            if (columnMapping.getUseDbObjectFlag()) {
                String dbExp = DbExpression.getDbExpression().getExpression(columnMapping.getDbExpression(), context.getDataSourceTypeEnums());
                valstrBuilder.append(dbExp);
            } else {
                valstrBuilder.append(DalConstants.SQL_PLACE_HOlDER);
                Object obj = context.getData().getObjectFieldValue(columnMapping.getFieldName());
                pList.add(obj);
            }
            if (index + 1 < columnMappings.size()) {
                colstrBuilder.append(DalConstants.SQL_SEPARATION);
                valstrBuilder.append(DalConstants.SQL_SEPARATION);
            }
        }
        String sql = String.format(getSQL(), context.getNameConvert().toName(context.getTableInfo().getName()), colstrBuilder, valstrBuilder);
        log.info(sql);
        return new SqlExpression(sql, pList,context.getDataSourceTypeEnums());
    }
}
